package tool;

import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONObject;
import com.alibaba.fastjson.parser.Feature;

public class MultiLayerJsonRepairer {

    /**
     * 修复多层转义的JSON字符串
     */
    public static String repairMultiLayerJson(String jsonString) {
        if (jsonString == null || jsonString.trim().isEmpty()) {
            return "{}";
        }

        try {
            // 1. 首先尝试直接解析
            JSONObject parsed = JSON.parseObject(jsonString,
                    Feature.AllowSingleQuotes,
                    Feature.AllowUnQuotedFieldNames,
                    Feature.AllowArbitraryCommas
            );

            // 2. 递归处理所有嵌套的JSON字符串字段
            processNestedJsonFields(parsed);

            return JSON.toJSONString(parsed, true);
        } catch (Exception e) {
            // 3. 如果直接解析失败，尝试逐步去除转义层
            return tryStepByStepUnescaping(jsonString);
        }
    }

    /**
     * 递归处理嵌套的JSON字段
     */
    private static void processNestedJsonFields(JSONObject json) {
        for (String key : json.keySet()) {
            Object value = json.get(key);

            if (value instanceof String) {
                String strValue = (String) value;

                // 检查是否是嵌套的JSON字符串
                if (isLikelyJsonString(strValue)) {
                    try {
                        // 尝试解析嵌套的JSON
                        Object nested = tryParseNestedJson(strValue);
                        json.put(key, nested);

                        // 如果是JSON对象，递归处理
                        if (nested instanceof JSONObject) {
                            processNestedJsonFields((JSONObject) nested);
                        }
                    } catch (Exception e) {
                        // 如果解析失败，保留原始值
                    }
                }
            } else if (value instanceof JSONObject) {
                // 递归处理嵌套对象
                processNestedJsonFields((JSONObject) value);
            }
        }
    }

    /**
     * 尝试解析嵌套的JSON字符串
     */
    private static Object tryParseNestedJson(String str) {
        // 尝试直接解析
        try {
            return JSON.parse(str,
                    Feature.AllowSingleQuotes,
                    Feature.AllowUnQuotedFieldNames,
                    Feature.AllowArbitraryCommas
            );
        } catch (Exception e) {
            // 如果直接解析失败，尝试去除一层转义
            String unescaped = unescapeJsonString(str);
            if (!unescaped.equals(str)) {
                return tryParseNestedJson(unescaped);
            }

            // 如果去除转义后还是无法解析，返回原始字符串
            return str;
        }
    }

    /**
     * 检查字符串是否可能是JSON
     */
    private static boolean isLikelyJsonString(String str) {
        if (str == null || str.length() < 2) {
            return false;
        }

        String trimmed = str.trim();
        return (trimmed.startsWith("{") && trimmed.endsWith("}")) ||
                (trimmed.startsWith("[") && trimmed.endsWith("]")) ||
                (trimmed.startsWith("\"") && trimmed.endsWith("\"") &&
                        trimmed.length() > 2 && trimmed.contains(":"));
    }

    /**
     * 去除JSON字符串中的一层转义
     */
    private static String unescapeJsonString(String jsonStr) {
        if (jsonStr == null || jsonStr.isEmpty()) {
            return jsonStr;
        }

        // 检查字符串是否被多余的引号包裹
        String trimmed = jsonStr.trim();
        if (trimmed.startsWith("\"") && trimmed.endsWith("\"")) {
            trimmed = trimmed.substring(1, trimmed.length() - 1);
        }

        // 替换转义的双引号
        String unescaped = trimmed.replace("\\\"", "\"");
        // 替换转义的反斜杠
        unescaped = unescaped.replace("\\\\", "\\");

        return unescaped;
    }

    /**
     * 尝试逐步去除转义层
     */
    private static String tryStepByStepUnescaping(String jsonString) {
        // 尝试多次去除转义，直到可以解析为止
        for (int i = 0; i < 5; i++) {
            try {
                String unescaped = unescapeJsonString(jsonString);
                if (unescaped.equals(jsonString)) {
                    break; // 没有再变化，停止尝试
                }

                JSONObject parsed = JSON.parseObject(unescaped,
                        Feature.AllowSingleQuotes,
                        Feature.AllowUnQuotedFieldNames,
                        Feature.AllowArbitraryCommas
                );

                // 处理嵌套字段
                processNestedJsonFields(parsed);
                return JSON.toJSONString(parsed, true);
            } catch (Exception e) {
                // 继续尝试下一层
                jsonString = unescapeJsonString(jsonString);
            }
        }

        // 如果所有尝试都失败，返回空对象
        return "{}";
    }


    // 测试方法
    public static void main(String[] args) {
        String s = "{\"method\"\"ResourceBackListener.process\",\"requestData\":\"\\\"{\\\\\\\"commandCategoryId\\\\\\\":4833146901715356113,\\\\\\\"instanceId\\\\\\\":4823634116090372483,\\\\\\\"isError\\\\\\\":\\\\\\\"true\\\\\\\",\\\\\\\"requestId\\\\\\\":\\\\\\\"d1d7256c-cc83-4f88-a3d7-1b0b242800ce\\\\\\\",\\\\\\\"serverType\\\\\\\":\\\\\\\"1834\\\\\\\",\\\\\\\"requestParams\\\\\\\":\\\\\\\"{\\\\\\\\\\\\\\\"tenant_id\\\\\\\\\\\\\\\":\\\\\\\\\\\\\\\"4813278056586346510\\\\\\\",\\\\\\\\\\\\\\\"cloud_code\\\\\\\\\\\\\\\":\\\\\\\\\\\\\\\"wocloud\\\\\\\\\\\\\\\",\\\\\\\\\\\\\\\"region_id\\\\\\\\\\\\\\\":4813278056586346496,\\\\\\\\\\\\\\\"action\\\\\\\\\\\\\\\":\\\\\\\\\\\\\\\"instanceBackup.wal.create\\\\\\\\\\\\\\\",\\\\\\\\\\\\\\\"type\\\\\\\\\\\\\\\":\\\\\\\\\\\\\\\"pgrds\\\\\\\\\\\\\\\",\\\\\\\\\\\\\\\"request_id\\\\\\\\\\\\\\\":\\\\\\\\\\\\\\\"d1d7256c-cc83-4f88-a3d7-1b0b242800ce\\\\\\\\\\\\\\\",\\\\\\\\\\\\\\\"url_param\\\\\\\\\\\\\\\":{\\\\\\\\\\\\\\\"instanceId\\\\\\\\\\\\\\\":4822198789559607704,\\\\\\\\\\\\\\\"rds_id\\\\\\\\\\\\\\\":\\\\\\\\\\\\\\\"ebb12984-76b1-417e-a918-4288acc3443b\\\\\\\\\\\\\\\"}}\\\\\\\",\\\\\\\"responseParams\\\\\\\":\\\\\\\"{\\\\\\\\\\\\\\\"code\\\\\\\\\\\\\\\":422,\\\\\\\\\\\\\\\"data\\\\\\\\\\\\\\\":{\\\\\\\\\\\\\\\"unprocessedEntity\\\\\\\\\\\\\\\":{\\\\\\\\\\\\\\\"code\\\\\\\\\\\\\\\":422,\\\\\\\\\\\\\\\"message\\\\\\\\\\\\\\\":\\\\\\\\\\\\\\\"No WAL file(s) to backup from instance ebb12984-76b1-417e-a918-4288acc3443b.\\\\\\\\\\\\\\\"}},\\\\\\\\\\\\\\\"requestId\\\\\\\\\\\\\\\":\\\\\\\\\\\\\\\"d1d7256c-cc83-4f88-a3d7-1b0b242800ce\\\\\\\\\\\\\\\"}\\\\\\\",\\\\\\\"methodCode\\\\\\\":\\\\\\\"instanceBackup.wal.create\\\\\\\"}\\\"\",\"requestMethod\":\"QUEUE\",\"responseData\":\"null\",\"serviceCode\":\"server\",\"url\":\"resource_back_queue\"}";

        String ss = "{\\\"commandCategoryId\\\":4833146901715356113,\\\"instanceId\\\":4823634116090372483,\\\"isError\\\":\\\"true\\\",\\\"requestId\\\":\\\"d1d7256c-cc83-4f88-a3d7-1b0b242800ce\\\",\\\"serverType\\\":\\\"1834\\\",\\\"requestParams\\\":\\\"{\\\\\\\"tenant_id\\\\\\\":\\\\\\\"4813278056586346510\\\\\\\",\\\\\\\"cloud_code\\\\\\\":\\\\\\\"wocloud\\\\\\\",\\\\\\\"region_id\\\\\\\":4813278056586346496,\\\\\\\"action\\\\\\\":\\\\\\\"instanceBackup.wal.create\\\\\\\",\\\\\\\"type\\\\\\\":\\\\\\\"pgrds\\\\\\\",\\\\\\\"request_id\\\\\\\":\\\\\\\"d1d7256c-cc83-4f88-a3d7-1b0b242800ce\\\\\\\",\\\\\\\"url_param\\\\\\\":{\\\\\\\"instanceId\\\\\\\":4822198789559607704,\\\\\\\"rds_id\\\\\\\":\\\\\\\"ebb12984-76b1-417e-a918-4288acc3443b\\\\\\\"}}\\\",\\\"responseParams\\\":\\\"{\\\\\\\"code\\\\\\\":422,\\\\\\\"data\\\\\\\":{\\\\\\\"unprocessedEntity\\\\\\\":{\\\\\\\"code\\\\\\\":422,\\\\\\\"message\\\\\\\":\\\\\\\"No WAL file(s) to backup from instance ebb12984-76b1-417e-a918-4288acc3443b.\\\\\\\"}},\\\\\\\"requestId\\\\\\\":\\\\\\\"d1d7256c-cc83-4f88-a3d7-1b0b242800ce\\\\\\\"}\\\",\\\"methodCode\\\":\\\"instanceBackup.wal.create\\\"}";

        //尝试通用修复方法
        String repairedJson = repairMultiLayerJson(s);
        System.out.println(JSONObject.parseObject(repairedJson));

    }
}